<template>
  <div>
    <div className="hello">
      <div style="height: 0px">
        <strong style="display: block; margin-top: 10px; text-align: center; font-size: 40px"
          >QPF(光流法)</strong
        >
      </div>
      <div className="box">
        <div className="map">
          <div id="map" ref="map"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, onUnmounted, ref, reactive, watch } from "vue";
import geoJson from "@/assets/yuegangao.json";
import regionStylesData from "@/assets/regionStyles.json";
import { useStore } from "vuex";
import { getQPFData } from "@/api/user/qpf";
import L from "leaflet";
import pako from "pako";

export default {
  name: "qpfgl",
  props: {
    totalData: {
      default: null,
    },
  },
  mounted() {
    this.$emit("changeTimeIndex", 6);
    this.$emit("changeIsSelect2", false);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", true);
  },
  setup(props) {
    const totalData = reactive(props.totalData);
    console.log(totalData, "111");
    watch(
      () => props.totalData,
      (newVal) => {
        console.log("totalData 发生了更改", newVal);
        totalData.value = newVal;
        params.year = newVal.startTime.getFullYear();
        params.month = newVal.startTime.getMonth() + 1;
        params.day = newVal.startTime.getDate();
        params.hour = newVal.startTime.getHours();
        params.minute = newVal.startTime.getMinutes();
        params.predict = newVal.predictTime;
        console.log("new params:", params);
        updateMap();
      },
      { deep: true }
    );
    const store = useStore();
    let mymap;
    var geojsonLayer;
    let cooData = ref([]);
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10,
    };

    let params = {
      year: 2023,
      month: 9,
      day: 9,
      hour: 23,
      minute: 54,
      predict: 6,
    };
    const COLORS = [
      "#00ECEC",
      "#003CF6",
      "#0000F6",
      "#00FE00",
      "#00C800",
      "#009000",
      "#FEFE00",
      "#E6C000",
      "#FE9000",
      "#FE0000",
      "#A60000",
      "#640000",
      "#CC00FF",
      "#9854C8",
    ];

    onMounted(() => {
      initMap();
      updateMap();
    });
    onUnmounted(() => {
      if (mymap) {
        mymap.remove();
        mymap = null;
      }
    });

    async function initMap() {
      const guangdongCenter = [23.125178, 113.280637];
      mymap = L.map("map", { attributionControl: false }).setView(
        guangdongCenter,
        7
      );
      mymap.setMinZoom(4);
      mymap.setMaxZoom(10);

      // 切换底图
      //矢量地图
      const tileLayer1 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地图
      const tileLayer2 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //矢量地名
      const tileLayer3 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      //影像地名
      const tileLayer4 = L.tileLayer(
        "http://t{s}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk={accessToken}",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          accessToken: "c9b286829db376e723c3dbed98c1b25e", // 替换为自己的访问令牌
        }
      );
      const baseMaps = {
        区划图: L.layerGroup([tileLayer1, tileLayer3]),
        地形图: L.layerGroup([tileLayer2, tileLayer4]),
      };
      tileLayer1.addTo(mymap);
      tileLayer3.addTo(mymap);
      L.control.layers(baseMaps).addTo(mymap);

      // 中国边界GeoJSON图层
      L.geoJSON(geoJson, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
          fillOpacity: 0.1,
        },
      }).addTo(mymap);

      function highlightFeature(e) {
        const layer = e.target;
        layer.setStyle({
          weight: 3,
          color: "#767676",
          fillColor: "#767676",
          dashArray: "",
          fillOpacity: 0.7,
        });
        layer.bringToFront();
      }

      function resetHighlight(e) {
        geojson.resetStyle(e.target);
      }

      // function zoomToFeature(e) {
      // 	map.fitBounds(e.target.getBounds());
      // }

      function onEachFeature(feature, layer) {
        layer.on({
          mouseover: highlightFeature,
          mouseout: resetHighlight,
          // click: zoomToFeature
        });
      }

      // 广东边界GeoJSON图层
      const geojson = L.geoJSON(regionStylesData, {
        style: {
          fillColor: "none",
          fillOpacity: 0,
          color: "black",
          weight: 1,
        },
        onEachFeature,
      }).addTo(mymap);

      //色标控件
      const legend = L.control({ position: "bottomright" });
      legend.onAdd = function (map) {
        const div = L.DomUtil.create("div", "legend");
        const grades = [
          0.1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 75, 100, 150, 250,
        ];
        const colors = [];
        const labels = [];
        for (let i = 0; i < grades.length - 1; i++) {
          let from = grades[i];
          if (i===0){
            colors.push(
              `<i style="background: ${COLORS[i]};width: 28px; margin-left:8px; height: 12px; float: left; opacity: 0.76;"></i>`
            );
          }else{
            colors.push(
              `<i style="background: ${COLORS[i]};width: 28px; height: 12px; float: left; opacity: 0.76;"></i>`
            );
          }
          labels.push(
            `<i style="width: 28px; height: 18px; text-align: left; float: left; font-style: normal;">${from}</i>`
          );
        }
        // 单独处理最后一个标签，以确保它位于最后一个色块的结束处
        labels.push(`<i style="width: 28px; height: 18px; text-align: left; float: left; font-style: normal;">${grades[grades.length - 1]}</i>`);
        div.innerHTML = `<div style="background-color: white; width: 428px; height: 60px; padding:4px">
                   <h3 style=" text-align: center;">降水估测（单位：mm）</h3>
                   ${colors.join("") + "<br>" + labels.join("")}</div>`;
        return div;
      };
      legend.addTo(mymap);

      return mymap;
    }

    async function updateMap() {
      cooData.value = await fetchData(params);
      let data = cooData.value;
      // console.log(data);

      if (data === null) {
        showTopMessage("当前时间没有相关数据", 2000);
      } else {
        // // 创建一个Blob对象
        let blob = new Blob([data.data], { type: "image/png" });
        const imageUrl = URL.createObjectURL(blob); // 将Blob转换为URL

        if (geojsonLayer) {
          mymap.removeLayer(geojsonLayer);
        }
        // 指定图片应该覆盖的地理范围
        const imageBounds = [[27, 108.5], [18.2, 119]];
        // 使用L.imageOverlay在指定范围内添加图片到地图上
        geojsonLayer = L.imageOverlay(imageUrl, imageBounds);
        geojsonLayer.addTo(mymap);
      }
    }

    async function fetchData(params) {
      try {
        const Data = await getQPFData(params); // 使用接口文件中的函数获取数据
        return Data;
      } catch (error) {
        console.error("Error fetching COO data:", error);
        return null;
      }
    }

    function showTopMessage(message, duration) {
      // 创建一个提示元素
      const messageElement = document.createElement("div");
      messageElement.className = "top-message";
      messageElement.textContent = message;

      // 将提示元素添加到页面的顶部
      document.body.appendChild(messageElement);

      // 设置定时器，在一定时间后自动隐藏提示
      setTimeout(() => {
        messageElement.style.opacity = "0"; // 渐变消失
        setTimeout(() => {
          document.body.removeChild(messageElement); // 删除提示元素
        }, 1000); // 在渐变结束后删除元素
      }, duration);

      // 自定义样式
      messageElement.style.position = "fixed";
      messageElement.style.top = "100px";
      messageElement.style.left = "42%";
      messageElement.style.width = "300px";
      messageElement.style.borderRadius = "4px";
      messageElement.style.backgroundColor = "#88bffa";
      messageElement.style.color = "#fff";
      messageElement.style.padding = "10px 0";
      messageElement.style.textAlign = "center";
      messageElement.style.transition = "opacity 1s ease-in-out";
    }

    return {
      totalData,
    };
  },
};
</script>

<style scoped lang="scss">
.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (min-width: 700px) {
  .map {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #map {
      width: 100%;
      height: 65vh;
    }
  }
}
</style>
